<template>
    <el-button plain type="primary" style="margin-bottom: 10px;" @click="Open()">添加</el-button>
    <el-button plain type="warning" style="float: right;" @click="openMaterialAskRecords()">我的物料申请</el-button>
    <el-button plain type="primary" style="float: right;" @click="Open()">导出</el-button>
    <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed type="index" label="序号" width="60" />
        <el-table-column prop="productMaterialsCode" label="物料编号" width="150" />
        <el-table-column prop="productMaterialsName" label="物料名称" width="150" />
        <el-table-column prop="productMaterialsType" label="规格型号" width="180" />
        <el-table-column prop="productMaterialsUnit" label="单位" width="180" />
        <el-table-column prop="materialGroupType" label="物料类型" width="180" />
        <el-table-column prop="productMaterialsDesc" label="产品物料描述" width="180" />
        <el-table-column prop="currentInventory" label="当前库存" width="180" />
        <el-table-column prop="inventoryCap" label="库存上限" width="180" />
        <el-table-column prop="inventoryFloor" label="库存下限" width="180" />
        <!-- <el-table-column prop="createrPeople" label="创建人" width="130" />
        <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
            </template>
</el-table-column>
<el-table-column prop="updateTime" label="修改时间" width="180">
    <template #default="scope">
                {{ moment(scope.row.updateTime).format('YYYY-MM-DD') }}
            </template>
</el-table-column> -->
        <el-table-column fixed="right" label="操作" min-width="100">
            <template v-slot="scope">
                <el-button link type="warning" @click="OpenUpdate(scope.row)">编辑</el-button>
                <el-button link type="danger" @click="Del(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 添加仓库物料弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加仓库物料" width="500px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
            <el-form-item label="库存上限" prop="inventoryCap">
                <el-input v-model="ruleForm.inventoryCap" placeholder="请输入产库存上限" />
            </el-form-item>
            <el-form-item label="库存下限" prop="inventoryFloor">
                <el-input v-model="ruleForm.inventoryFloor" placeholder="请输入库存下限" />
            </el-form-item>
            <el-form-item label="当前库存" prop="currentInventory">
                <el-input v-model="ruleForm.currentInventory" type="textarea" placeholder="请输入当前库存" />
            </el-form-item>

            <el-form-item label="所属仓库" prop="warehouseId">
                <el-select v-model="ruleForm.warehouseId" placeholder="请选择仓库">
                    <el-option v-for="item in WaretableData" :label="item.warehouseName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属物料群组" prop="materialGroupId">
                <el-select v-model="ruleForm.materialGroupId" placeholder="请选择物料群组" @change="GetProductMaterials()">
                    <el-option v-for="item in MaterialGrouptableData" :label="item.materialGroupName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属物料" prop="productMaterialsId">
                <el-select v-model="ruleForm.productMaterialsId" placeholder="请选择物料">
                    <el-option v-for="item in ProductMaterialstableData" :label="item.productMaterialsName"
                        :value="item.id" />
                </el-select>
            </el-form-item>


        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 修改仓库物料弹窗 -->
    <el-dialog v-model="dialogVisibleUpdate" title="修改产线" width="500px">
        <el-form ref="ruleFormRef" :model="ruleFormUpdate" :rules="rules" label-width="120px">
            <el-form-item label="库存上限" prop="inventoryCap">
                <el-input v-model="ruleFormUpdate.inventoryCap" placeholder="请输入产库存上限" />
            </el-form-item>
            <el-form-item label="库存下限" prop="inventoryFloor">
                <el-input v-model="ruleFormUpdate.inventoryFloor" placeholder="请输入库存下限" />
            </el-form-item>
            <el-form-item label="当前库存" prop="currentInventory">
                <el-input v-model="ruleFormUpdate.currentInventory" type="textarea" placeholder="请输入当前库存" />
            </el-form-item>

            <el-form-item label="所属仓库" prop="warehouseId">
                <el-select v-model="ruleFormUpdate.warehouseId" placeholder="请选择仓库">
                    <el-option v-for="item in WaretableData" :label="item.warehouseName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属物料群组" prop="materialGroupId">
                <el-select v-model="ruleFormUpdate.materialGroupId" placeholder="请选择物料群组"
                    @change="GetProductMaterials()">
                    <el-option v-for="item in MaterialGrouptableData" :label="item.materialGroupName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属物料" prop="productMaterialsId">
                <el-select v-model="ruleFormUpdate.productMaterialsId" placeholder="请选择物料">
                    <el-option v-for="item in ProductMaterialstableData" :label="item.productMaterialsName"
                        :value="item.id" />
                </el-select>
            </el-form-item>


        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- <el-dialog v-model="dialogVisibleUpdate" title="修改产线" width="500px">
        <el-form ref="ruleFormRef" :model="ruleFormUpdate" :rules="rules" label-width="120px">
         
            <el-form-item label="所属车间" prop="workShopId">
                <el-select v-model="ruleFormUpdate.materialGroupId" placeholder="请选择车间">
                    <el-option v-for="item in MaterialGrouptableData" :label="item.materialGroupName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog> -->
    <!--分页-->
    <el-pagination v-model:current-page="page.Index" v-model:page-size="page.Size" :page-sizes="[5, 10, 20, 30]"
        :background="true" layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount" />

    <!-- 库存不足确认弹窗 -->
    <el-dialog v-model="inventoryShortageDialogVisible" title="库存不足提示" width="500px" :close-on-click-modal="false">
        <div class="shortage-info">
            <el-icon class="warning-icon"><Warning /></el-icon>
            <div class="shortage-content">
                <h3>库存量不足</h3>
                <p><strong>物料名称：</strong>{{ currentShortageItem.productMaterialsName }}</p>
                <p><strong>当前库存：</strong>{{ currentShortageItem.currentInventory }}</p>
                <p><strong>申请出库数量：</strong>{{ shortageRequestCount }}</p>
                <p><strong>缺少数量：</strong>{{ shortageRequestCount - currentShortageItem.currentInventory }}</p>
                <div class="shortage-question">
                    <p>是否申请采购补充库存？</p>
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancelShortageDialog">取消</el-button>
                <el-button type="primary" @click="goToPurchaseRequest">是，申请采购</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 物料申请记录对话框 -->
    <el-dialog v-model="materialAskDialogVisible" title="" width="80%">
        <el-table :data="materialAskList" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="materialAskCode" label="申请单号" width="120" />
            <el-table-column prop="productMaterialsName" label="物料名称" width="150" />
            <el-table-column prop="materialAskCount" label="申请数量" width="100" />
            <el-table-column prop="materialAskUnit" label="单位" width="80" />
            <el-table-column prop="materialAskDesc" label="申请描述" min-width="200" />
            <el-table-column prop="materialAskStatus" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.materialAskStatus)">
                        {{ scope.row.materialAskStatus }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="createrPeople" label="创建人" width="100" />
            <el-table-column fixed="right" label="操作" width="180">
                <template #default="scope">
                    <!-- 根据状态显示不同的操作按钮 -->
                    <span v-if="isMaterialAskCompleted(scope.row)" class="completed-status">出库成功</span>
                    <div v-else class="operation-buttons">
                    <el-button 
                        link 
                        type="success" 
                        @click="openMaterialOutDialog(scope.row)"
                    >
                            手动出库
                    </el-button>
                        <el-button 
                            link 
                            type="primary" 
                            @click="openBarcodeDialog(scope.row)"
                        >
                            一维码出库
                        </el-button>
                    </div>
                </template>
            </el-table-column>

        </el-table>

        <div class="pagination-container">
            <el-pagination v-model:current-page="materialAskPagination.currentPage"
                v-model:page-size="materialAskPagination.pageSize" :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper" :total="materialAskPagination.total"
                @size-change="handleMaterialAskSizeChange" @current-change="handleMaterialAskCurrentChange" />
        </div>
    </el-dialog>

    <!-- 物料出库弹窗 -->
    <el-dialog v-model="materialOutDialogVisible" title="物料出库" width="500px">
        <el-form ref="materialOutFormRef" style="max-width: 600px" :model="materialOutForm" :rules="materialOutRules" label-width="auto">
            <el-form-item label="出库编号" prop="outInCode">
                <div style="display: flex; gap: 10px;">
                    <el-input v-model="materialOutForm.outInCode" :disabled="isMaterialOutCodeGenerated" />
                    <el-button type="primary" @click="generateMaterialOutCode" :disabled="isMaterialOutCodeGenerated">
                        {{ isMaterialOutCodeGenerated ? '已生成' : '生成编号' }}
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item label="物料名称" prop="productMaterialsName">
                <el-input v-model="materialOutForm.productMaterialsName" disabled />
            </el-form-item>
            <el-form-item label="申请单号" prop="materialAskCode">
                <el-input v-model="materialOutForm.materialAskCode" disabled />
            </el-form-item>
            <el-form-item label="申请数量" prop="requestCount">
                <el-input v-model="materialOutForm.requestCount" disabled />
            </el-form-item>
            <el-form-item label="出库数量" prop="outInCount">
                <div class="inventory-control">
                    <el-button class="inventory-btn" @click="decreaseMaterialOutCount">-</el-button>
                    <el-input v-model="materialOutForm.outInCount" class="inventory-input" />
                    <el-button class="inventory-btn" @click="increaseMaterialOutCount">+</el-button>
                </div>
            </el-form-item>
            <el-form-item style="padding-left: 400px;">
                <el-tag type="success">出库</el-tag>
            </el-form-item>
            <el-form-item>
                <el-button @click="materialOutDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitMaterialOutForm(materialOutFormRef)">确定出库</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 一维码出库弹窗 -->
    <el-dialog 
        v-model="barcodeDialogVisible" 
        title="一维码出库" 
        width="500px" 
        :close-on-click-modal="true"
        :show-close="true"
        :destroy-on-close="true"
        :before-close="handleBarcodeDialogClose"
        @keydown.enter.prevent
    >
        <div class="barcode-container" @submit.prevent>
            <h3>{{ currentMaterialAskItem.productMaterialsName }} - 出库一维码</h3>
            <p>申请单号: {{ currentMaterialAskItem.materialAskCode }}</p>
            <p>申请数量: {{ currentMaterialAskItem.materialAskCount }}</p>
            
            <!-- 一维码显示区域 -->
            <div class="barcode-display">
                <canvas ref="barcodeCanvas" class="barcode-canvas"></canvas>
            </div>
            
            <div class="barcode-instructions">
                <p>请使用扫码枪扫描上方一维码完成出库操作</p>
                <p class="barcode-note">扫描后系统将自动完成物料出库</p>
            </div>
            
            <!-- 扫码输入区域 -->
            <form @submit.prevent="handleBarcodeScan" class="scan-input-container">
                <el-input 
                    v-model="scanInputData" 
                    placeholder="扫码输入区域" 
                    class="scan-input"
                    @keydown.enter.stop.prevent="handleBarcodeScan($event)"
                    autofocus
                    type="text"
                ></el-input>
                <button type="submit" style="display: none;"></button>
            </form>
            
            <!-- 手动关闭按钮 -->
            <div class="dialog-footer" style="margin-top: 20px; text-align: center;">
                <el-button type="primary" @click="forceBarcodeDialogClose">关闭窗口</el-button>
            </div>
        </div>
    </el-dialog>

</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import { useRoute, useRouter } from 'vue-router';
import { Warning } from '@element-plus/icons-vue';
import JsBarcode from 'jsbarcode';


const pinia = useCounterStore();
const route = useRoute();
const router = useRouter();
const tableData = ref([])

// 库存不足弹窗相关数据
const inventoryShortageDialogVisible = ref(false);
const currentShortageItem = ref<any>({});
const shortageRequestCount = ref(0);

// 物料申请记录相关数据
const materialAskDialogVisible = ref(false);
const materialAskList = ref<any[]>([]);
const materialAskFilter = reactive({
    status: '',
    code: ''
});
const materialAskPagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
});

//物料库存向后端传参
const page = reactive({
    Index: 1,
    Size: 5,
    totalcount: 0
})
const pagee = reactive({
    PageIndex: 1,
    PageSize: 100,
    HangCount: 0
})
//钩子
/**
 * 记录按键事件
 */
const logKeyEvent = (event: KeyboardEvent) => {
    lastKeyPressed.value = `${event.key} (keyCode: ${event.keyCode})`;
    lastScanTime.value = Date.now();
    console.log('按键事件:', event.key, event.keyCode);
    
    // 如果是回车键，可能是扫码枪完成扫描
    if (event.key === 'Enter') {
        console.log('检测到回车键，可能是扫码枪完成扫描');
    }
};

/**
 * 处理扫码输入事件
 */
const onScanInput = (value: string) => {
    console.log('扫码输入事件触发:', value);
    lastScanTime.value = Date.now();
    
    // 检查是否是扫码枪快速输入（通常扫码枪输入速度非常快）
    if (value && value.length > 5) {
        console.log('可能是扫码枪输入，长度:', value.length);
    }
};

/**
 * 处理扫码变更事件
 */
const onScanChange = (value: string) => {
    console.log('扫码变更事件触发:', value);
    
    // 如果输入内容包含分隔符或符合特定格式，可能是扫码枪输入完成
    if (value && (value.includes('-') || value.length > 8)) {
        console.log('检测到可能的完整扫码输入，自动处理');
        // 延迟一点点时间，确保输入完成
        setTimeout(() => {
            handleBarcodeScan();
        }, 100);
    }
};

// 防止在扫码过程中发生导航
const preventNavigation = (event: Event) => {
    // 如果扫码对话框是打开的，阻止导航
    if (barcodeDialogVisible.value) {
        // 检查点击的元素是否是关闭按钮或其父元素
        const target = event.target as HTMLElement;
        
        // 允许关闭按钮和对话框叉号的点击事件
        if (target.classList.contains('el-button') || 
            target.closest('.el-button') || 
            target.classList.contains('el-dialog__close') || 
            target.closest('.el-dialog__close') || 
            target.classList.contains('el-dialog__headerbtn') || 
            target.closest('.el-dialog__headerbtn')) {
            console.log('允许关闭按钮或对话框叉号的点击事件');
            return true;
        }
        
        event.preventDefault();
        event.stopPropagation();
        console.log('阻止了可能的导航事件');
        return false;
    }
}

// 全局键盘事件处理函数
const handleGlobalKeydown = (e: KeyboardEvent) => {
    if (barcodeDialogVisible.value) {
        // 记录按键
        logKeyEvent(e);
        
        // 如果是回车键，可能是扫码完成
        if (e.key === 'Enter') {
            e.preventDefault();
            e.stopPropagation();
            console.log('全局捕获到回车键，触发扫码处理');
            handleBarcodeScan();
        }
    }
};

onMounted(() => {
    GetMaterialGroup()
    GetWare()
    GetWarehouse()

    // 如果URL中包含materialAskCode参数，表示从待办点击跳转过来
    const materialAskCode = route.query.materialAskCode as string;
    if (materialAskCode) {
        // 打开物料申请记录对话框并查询对应的申请单
        materialAskFilter.code = materialAskCode;
        openMaterialAskRecords();
    }
    
    // 添加全局事件监听器，防止在扫码过程中发生导航
    window.addEventListener('click', preventNavigation, true);
    window.addEventListener('submit', preventNavigation, true);
    
    // 添加全局键盘事件监听器，确保捕获扫码枪输入
    document.addEventListener('keydown', handleGlobalKeydown, true);
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
    window.removeEventListener('click', preventNavigation, true);
    window.removeEventListener('submit', preventNavigation, true);
    document.removeEventListener('keydown', handleGlobalKeydown, true);
})
watch(page, () => {
    GetWare();
})

//仓库物料显示
const GetWare = () => {
    axios.get('/api/ProductionModules/GetInventory', { params: page }).then(res => {
        if (res.data.code == 200) {
            tableData.value = res.data.data.totalPage
            page.totalcount = res.data.data.totalcount


        }
    })
}
// 控制弹窗显示
const dialogVisible = ref(false);
const Open = () => {
    dialogVisible.value = true;
}
///物料添加
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "warehouseId": "",
    "currentInventory": "",
    "inventoryCap": "",
    "inventoryFloor": "",
    "materialGroupId": "",
    "productMaterialsId": "",
})

const MaterialGrouptableData: any = ref([])
//物料群组网络传输
const GetMaterialGroup = () => {
    axios.get('/api/MaterialManagement/GetMaterialGroup', { params: pagee }).then(res => {
        if (res.data.code == 200) {
            MaterialGrouptableData.value = res.data.totalPage
            pagee.HangCount = res.data.HangCount
        }
    })
}
const ProductMaterialstableData: any = ref([])
//产品物料网络传输
const GetProductMaterials = () => {
    axios.get('/api/ProductionModules/GetMaterials', { params: { MaterialGroupId: ruleForm.materialGroupId } }).then(res => {
        if (res.data.code == 200) {
            ProductMaterialstableData.value = res.data.data

        }
    })
}
const WaretableData: any = ref([])
//仓库显示
const GetWarehouse = () => {
    axios.get('/api/ProductionModules/GetWare', { params: page }).then(res => {
        if (res.data.code == 200) {
            WaretableData.value = res.data.data.totalPage
            page.totalcount = res.data.data.totalcount
        }
    })
}

//验证
const rules = reactive<FormRules>({
    productionLineCode: [
        { required: true, message: '请输入产线编码', trigger: 'blur' },
    ],
    productionLineName: [
        {
            required: true,
            message: '请输入产线名称',
            trigger: 'blur',
        },
    ],
    workShopId: [
        {
            required: true,
            message: '请选择车间',
            trigger: 'blur',
        }],
    productionLineDesc: [
        {
            required: true,
            message: '请输入产线描述',
            trigger: 'blur',
        },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post('/api/ProductionModules/AddInventory', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);

                    dialogVisible.value = false;
                    GetWare(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
///修改产品物料
const dialogVisibleUpdate = ref(false);
const OpenUpdate = (row: any) => {
    dialogVisibleUpdate.value = true
    ruleFormUpdate.id = row.id
    ruleFormUpdate.warehouseId = row.warehouseId
    ruleFormUpdate.currentInventory = row.currentInventory
    ruleFormUpdate.inventoryCap = row.inventoryCap
    ruleFormUpdate.inventoryFloor = row.inventoryFloor
    ruleFormUpdate.materialGroupId = row.materialGroupId
    ruleFormUpdate.productMaterialsId = row.productMaterialsId
    ruleFormUpdate.outboundStatus = row.outboundStatus
}
const ruleFormUpdate = reactive({
    "id": "",
    "warehouseId": "",
    "currentInventory": "",
    "inventoryCap": "",
    "inventoryFloor": "",
    "materialGroupId": "",
    "productMaterialsId": "",
    "outboundStatus": "",

})
//修改网络
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.put('/api/ProductionModules/InventoryUpdateCommand', ruleFormUpdate).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    dialogVisibleUpdate.value = false;
                    GetWare(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const Del = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除该产线吗？删除后数据将无法恢复。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // axios.post(`/api/ProductionModules/DeleteInventory`, { row: row })
            axios({
                url: "/api/ProductionModules/DeleteInventory",
                method: 'post',
                data: row
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.message);
                        GetWare(); // 删除成功后刷新表格数据
                    } else {
                        ElMessage.error(res.data.message);
                    }
                }).catch(error => {
                    ElMessage.error('删除失败，请重试');
                    console.error('Delete error:', error);
                });
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
}

// 格式化日期
const formatDate = (dateString: string) => {
    if (!dateString) return '';
    return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 根据状态获取标签类型
const getStatusType = (status: string) => {
    switch (status) {
        case '进行中':
            return 'warning';
        case '已完成':
            return 'success';
        case '已取消':
            return 'danger';
        default:
            return 'info';
    }
};

// 打开物料申请记录对话框
const openMaterialAskRecords = () => {
    materialAskDialogVisible.value = true;
    // 重置分页
    materialAskPagination.currentPage = 1;
    // 查询物料申请记录
    fetchMaterialAskRecords();
};

// 查询物料申请记录
const fetchMaterialAskRecords = async () => {


    // 构建查询参数
    const params: any = {
        PageIndex: materialAskPagination.currentPage,
        PageSize: materialAskPagination.pageSize
    };

    // 调用API获取物料申请记录
    const response = await axios.get('/api/MaterialManagement/GetMaterialAsk', {
        params: params,
    });

    if (response.data.code === 200) {
        materialAskList.value = response.data.totalPage || [];
        materialAskPagination.total = response.data.totalcount || 0;
    } else {
        console.error('获取物料申请记录失败，错误码:', response.data.code, '错误信息:', response.data.message);
        ElMessage.error(`获取物料申请记录失败: ${response.data.message || '未知错误'}`);
    }
};

// 处理分页大小变化
const handleMaterialAskSizeChange = (size: number) => {
    materialAskPagination.pageSize = size;
    fetchMaterialAskRecords();
};

// 处理页码变化
const handleMaterialAskCurrentChange = (page: number) => {
    materialAskPagination.currentPage = page;
    fetchMaterialAskRecords();
};

// ==================== 物料出库相关功能 ====================

// 物料出库弹窗相关数据
const materialOutDialogVisible = ref(false);
const isMaterialOutCodeGenerated = ref(false);
const materialOutFormRef = ref<FormInstance>();
const currentMaterialAskItem = ref<any>({});

// 一维码相关数据
const barcodeDialogVisible = ref(false);
const barcodeCanvas = ref<HTMLCanvasElement | null>(null);
const barcodeData = ref(''); // 存储一维码数据（生成的条码格式）
const scanInputData = ref(''); // 存储扫码枪输入的数据
const lastKeyPressed = ref(''); // 存储最后按下的键
const lastScanTime = ref<number | null>(null); // 存储最后扫码时间


// 物料出库表单数据
const materialOutForm = reactive({
    "outInCode": "",
    "outIn": 1, // 1表示出库
    "outInCount": 0,
    "productMaterialsId": null as number | null,
    "productMaterialsName": "",
    "materialAskCode": "",
    "requestCount": 0,
    "createrPeople": pinia.piniaDto.realName
});

// 物料出库表单验证规则
const materialOutRules = reactive<FormRules>({
    outInCode: [
        { required: true, message: '请输入出库编号', trigger: 'blur' },
    ],
    outInCount: [
        {
            required: true,
            message: '请输入出库数量',
            trigger: 'change',
        },
    ],
});

/**
 * 判断物料申请是否已完成（出库完成）
 * @param row 物料申请记录行数据
 */
const isMaterialAskCompleted = (row: any) => {
    // 根据状态判断是否已完成
    // 假设状态为"已完成"或者数值为1表示已完成
    return row.materialAskStatus === '已完成' || Number(row.materialAskStatus) === 1;
};

/**
 * 打开物料出库弹窗
 * @param row 物料申请记录行数据
 */
const openMaterialOutDialog = (row: any) => {
    console.log('打开物料出库弹窗，申请记录数据:', row);
    
    // 保存当前申请记录信息
    currentMaterialAskItem.value = { ...row };
    
    // 重置表单
    materialOutForm.outInCode = "";
    isMaterialOutCodeGenerated.value = false;
    
    // 设置表单数据
    materialOutForm.productMaterialsId = row.productMaterialsId || row.id;
    materialOutForm.productMaterialsName = row.productMaterialsName || '';
    materialOutForm.materialAskCode = row.materialAskCode || '';
    materialOutForm.requestCount = row.materialAskCount || 0;
    materialOutForm.outInCount = row.materialAskCount || 0; // 默认出库数量等于申请数量
    
    // 显示弹窗
    materialOutDialogVisible.value = true;
};

/**
 * 打开一维码出库弹窗
 * @param row 物料申请记录行数据
 */
const openBarcodeDialog = (row: any) => {
    // 保存当前申请记录信息
    currentMaterialAskItem.value = { ...row };
    
    // 使用CODE128格式，它更灵活，不需要固定位数
    // 创建简短的数据格式：申请ID-物料ID-数量
    const askId = row.id || '0';
    const materialId = row.productMaterialsId || '0';
    const askCount = row.materialAskCount || '0';
    
    // 构建简单的一维码数据 - 使用长格式以匹配扫码枪输出
    // 格式：15位ID-16位物料ID-4位数量，确保与扫码枪输出格式匹配
    const paddedAskId = askId.toString().padStart(15, '0');
    const paddedMaterialId = materialId.toString().padStart(16, '0');
    const paddedAskCount = askCount.toString().padStart(4, '0');
    const barcodeContent = `${paddedAskId}-${paddedMaterialId}-${paddedAskCount}`;
    
    console.log('生成的一维码数据:', barcodeContent);
    
    // 保存一维码数据
    barcodeData.value = barcodeContent;
    
    // 清空扫码输入框
    scanInputData.value = '';
    
    // 重置调试信息
    lastKeyPressed.value = '';
    lastScanTime.value = null;
    
    // 显示弹窗
    barcodeDialogVisible.value = true;
    
    // 使用nextTick确保元素已经渲染
    nextTick(() => {
        // 生成一维码
        generateBarcode();
        
        // 聚焦到输入框，准备接收扫码枪输入
        const inputElement = document.querySelector('.scan-input input');
        if (inputElement) {
            (inputElement as HTMLInputElement).focus();
        }
    });
};

/**
 * 强制关闭一维码弹窗
 * 这个函数会移除所有事件监听器并关闭弹窗
 */
const forceBarcodeDialogClose = () => {
    console.log('强制关闭一维码弹窗');
    
    // 移除所有可能阻止关闭的事件监听器
    window.removeEventListener('click', preventNavigation, true);
    window.removeEventListener('submit', preventNavigation, true);
    document.removeEventListener('keydown', handleGlobalKeydown, true);
    
    // 重置状态并关闭弹窗
    scanInputData.value = '';
    barcodeDialogVisible.value = false;
    
    // 延迟后重新添加必要的事件监听器
    setTimeout(() => {
        document.addEventListener('keydown', handleGlobalKeydown, true);
    }, 1000);
    
    ElMessage.success('已关闭一维码出库窗口');
};

/**
 * 处理一维码弹窗关闭事件
 * @param done 关闭回调函数
 */
const handleBarcodeDialogClose = (done?: () => void) => {
    console.log('执行一维码弹窗关闭事件处理函数');
    
    // 清空扫码输入框
    scanInputData.value = '';
    
    // 重置相关状态
    barcodeDialogVisible.value = false;
    
    // 临时移除全局事件监听器，确保关闭操作不会被阻止
    window.removeEventListener('click', preventNavigation, true);
    window.removeEventListener('submit', preventNavigation, true);
    
    // 如果有done回调，则执行它
    if (done) {
        console.log('执行关闭回调');
        done();
    }
    
    // 延迟一点时间后重新添加全局事件监听器
    setTimeout(() => {
        // 只有当弹窗确实关闭后才重新添加事件监听器
        if (!barcodeDialogVisible.value) {
            window.addEventListener('click', preventNavigation, true);
            window.addEventListener('submit', preventNavigation, true);
        }
    }, 500);
};

/**
 * 生成标准货物一维码
 */
const generateBarcode = () => {
    if (barcodeCanvas.value) {
        try {
            // 使用JsBarcode生成符合标准的货物一维码
            JsBarcode(barcodeCanvas.value, barcodeData.value, {
                format: "CODE128", // 使用CODE128格式，更灵活，支持字母、数字和特殊字符
                width: 2,          // 条码宽度
                height: 80,        // 条码高度
                displayValue: true, // 显示文字值
                fontSize: 14,
                font: "Arial",
                textMargin: 8,
                background: "#ffffff",
                lineColor: "#000000",
                margin: 10
            });
            console.log('一维码生成成功');
        } catch (error) {
            console.error('生成一维码失败:', error);
            ElMessage.error('生成一维码失败');
            
            // 尝试使用备用格式
            try {
                JsBarcode(barcodeCanvas.value, barcodeData.value, {
                    format: "CODE39", // 备用格式
                    width: 2,
                    height: 80
                });
                console.log('使用CODE39格式生成成功');
            } catch (backupError) {
                console.error('备用格式也失败:', backupError);
                
                // 最后尝试最基本的格式
                try {
                    JsBarcode(barcodeCanvas.value, String(Date.now()), {
                        format: "CODE128",
                        width: 2,
                        height: 80
                    });
                    console.log('使用时间戳生成成功');
                } catch (finalError) {
                    console.error('所有尝试都失败:', finalError);
                }
            }
        }
    }
};

/**
 * 处理一维码扫描
 * @param event 键盘事件或表单事件对象
 */
const handleBarcodeScan = async (event?: KeyboardEvent | Event) => {
    try {
        // 记录调试信息
        console.log('=== 扫码处理开始 ===');
        console.log('当前时间:', new Date().toISOString());
        console.log('事件类型:', event ? event.constructor.name : '手动触发');
        
        // 阻止默认行为，防止表单提交或页面跳转
        if (event) {
            event.preventDefault();
            event.stopPropagation();
            
            // 如果是键盘事件，检查是否是回车键
            if ('key' in event) {
                console.log('键盘事件:', event.key, event.keyCode);
                // 确保不是其他键
                if (event.key !== 'Enter') {
                    console.log('非回车键，忽略处理');
                    return;
                }
            }
        }
        
        // 临时禁用页面上的所有按钮，防止意外点击
        const allButtons = document.querySelectorAll('button, a, .el-button');
        console.log(`临时禁用 ${allButtons.length} 个按钮`);
        allButtons.forEach(btn => {
            if (btn instanceof HTMLElement) {
                btn.setAttribute('disabled', 'disabled');
                // 2秒后恢复
                setTimeout(() => {
                    btn.removeAttribute('disabled');
                }, 2000);
            }
        });
        
        // 记录扫描数据
        console.log('原始条码数据:', barcodeData.value);
        console.log('扫码枪输入数据:', scanInputData.value);
        
        // 获取扫描的数据 - 尝试多种数据源
        let scannedData = '';
        
        // 1. 首先尝试使用扫码枪输入的数据（如果有）
        if (scanInputData.value && scanInputData.value.trim()) {
            console.log('使用扫码枪输入的数据');
            scannedData = scanInputData.value.trim();
        } 
        // 2. 如果没有扫码枪输入，则使用原始条码数据
        else if (barcodeData.value && barcodeData.value.trim()) {
            console.log('使用原始条码数据');
            scannedData = barcodeData.value.trim();
        }
        
        console.log('最终使用的扫描数据:', scannedData);
        
        // 如果没有任何数据，直接使用当前申请记录信息
        if (!scannedData && currentMaterialAskItem.value) {
            console.log('无扫描数据，直接使用当前申请记录');
            executeOutbound(
                currentMaterialAskItem.value.id,
                currentMaterialAskItem.value.productMaterialsId,
                currentMaterialAskItem.value.materialAskCount
            );
            return;
        }
        
        // 解析扫描数据
        let parts: string[] = [];
        
        // 特殊处理：检测是否是扫码枪扫描的特定格式（如：723452844113925-7160720116326-7000）
        // 使用更灵活的正则表达式匹配长数字-长数字-数字格式
        const longCodeRegex = /^\d{10,}-\d{10,}-\d{1,}$/;
        if (longCodeRegex.test(scannedData)) {
            console.log('检测到特定格式的扫码数据，直接使用当前申请记录');
            // 对于这种特殊格式，我们直接使用当前申请记录的信息
            if (currentMaterialAskItem.value) {
                parts = [
                    String(currentMaterialAskItem.value.id || '0'),
                    String(currentMaterialAskItem.value.productMaterialsId || '0'),
                    String(currentMaterialAskItem.value.materialAskCount || '0')
                ];
                console.log('使用当前申请记录信息:', parts);
            } else {
                // 如果没有当前申请记录，尝试从扫码数据中提取数量
                const lastPart = scannedData.split('-').pop() || '0';
                const quantity = parseInt(lastPart);
                console.log('从扫码数据中提取数量:', quantity);
                
                // 使用默认ID和从扫码数据中提取的数量
                parts = ['0', '0', String(quantity)];
            }
        } else {
            // 尝试各种可能的分隔符
            const separators = ['-', ',', ' ', ':', ';', '|'];
            for (const sep of separators) {
                if (scannedData.includes(sep)) {
                    console.log(`使用分隔符 "${sep}" 解析数据`);
                    parts = scannedData.split(sep);
                    break;
                }
            }
            
            // 如果没有找到分隔符，尝试按固定位数分割
            if (parts.length === 0) {
                console.log('尝试按固定位数分割扫码数据');
                const len = scannedData.length;
                
                // 尝试不同的分割方式
                if (len >= 9) {
                    // 尝试 3-3-3 分割
                    parts = [
                        scannedData.substring(0, 3),
                        scannedData.substring(3, 6),
                        scannedData.substring(6, 9)
                    ];
                } else if (len >= 6) {
                    // 尝试 2-2-2 分割
                    parts = [
                        scannedData.substring(0, 2),
                        scannedData.substring(2, 4),
                        scannedData.substring(4)
                    ];
                } else if (len >= 3) {
                    // 尝试 1-1-剩余 分割
                    parts = [
                        scannedData.substring(0, 1),
                        scannedData.substring(1, 2),
                        scannedData.substring(2)
                    ];
                }
            }
        }
        
        console.log('解析扫码数据结果:', parts);
        
        // 如果仍然无法解析，但扫码数据中包含分隔符"-"，尝试提取最后一部分作为数量
        if (parts.length !== 3 && scannedData.includes('-')) {
            console.log('尝试从带分隔符的扫码数据中提取数量');
            const segments = scannedData.split('-');
            const lastSegment = segments[segments.length - 1];
            
            // 尝试解析最后一段为数字
            if (/^\d+$/.test(lastSegment)) {
                const quantity = parseInt(lastSegment);
                console.log('从扫码数据中提取到数量:', quantity);
                
                if (currentMaterialAskItem.value) {
                    // 使用当前申请记录的ID和物料ID，但使用扫码中提取的数量
                    parts = [
                        String(currentMaterialAskItem.value.id || '0'),
                        String(currentMaterialAskItem.value.productMaterialsId || '0'),
                        String(quantity)
                    ];
                } else {
                    // 如果没有当前申请记录，使用默认ID和扫码中提取的数量
                    parts = ['0', '0', String(quantity)];
                }
            }
        }
        
        // 如果上述方法都失败，直接使用当前申请记录的信息
        if (parts.length !== 3 && currentMaterialAskItem.value) {
            console.log('无法解析扫码数据，使用当前申请记录信息');
            parts = [
                String(currentMaterialAskItem.value.id || '0'),
                String(currentMaterialAskItem.value.productMaterialsId || '0'),
                String(currentMaterialAskItem.value.materialAskCount || '0')
            ];
        }
        
        // 强制处理，即使解析失败也尝试执行出库
        // 确保parts有3个元素
        while (parts.length < 3) {
            parts.push('0');
            console.log('数据不完整，添加默认值0');
        }
        
        // 解析数据并执行出库
        const askId = parseInt(parts[0]) || 0;
        const materialId = parseInt(parts[1]) || 0;
        const askCount = parseInt(parts[2]) || 0;
        
        console.log('最终解析结果:', { askId, materialId, askCount });
        
        // 执行出库操作
        await executeOutbound(askId, materialId, askCount);
    } catch (error) {
        console.error('处理扫码失败:', error);
        ElMessage.error('处理扫码失败，请重试');
        
        // 尝试使用应急方案 - 直接使用当前申请记录强制出库
        try {
            if (currentMaterialAskItem.value && currentMaterialAskItem.value.id) {
                console.log('尝试应急出库方案...');
                await executeOutbound(
                    currentMaterialAskItem.value.id,
                    currentMaterialAskItem.value.productMaterialsId,
                    currentMaterialAskItem.value.materialAskCount,
                    true // 应急模式
                );
            }
        } catch (emergencyError) {
            console.error('应急出库也失败:', emergencyError);
            ElMessage.error('所有出库尝试均失败，请手动处理');
        }
    }
};

/**
 * 执行出库操作
 * @param askId 申请ID
 * @param materialId 物料ID
 * @param askCount 申请数量
 * @param isEmergency 是否是应急模式
 */
const executeOutbound = async (askId: number, materialId: number, askCount: number, isEmergency: boolean = false) => {
    try {
        console.log(`执行${isEmergency ? '应急' : '正常'}出库操作:`, { askId, materialId, askCount });
        
        // 首先检查库存是否充足
        // 根据物料ID查找当前库存信息
        const currentInventoryItem = tableData.value.find((item: any) => 
            item.productMaterialsId === materialId || 
            item.id === materialId
        );
        
        console.log('找到的库存信息:', currentInventoryItem);
        console.log('申请出库数量:', askCount);
        
        if (currentInventoryItem) {
            const currentInventory = Number((currentInventoryItem as any).currentInventory) || 0;
            const requestOutCount = Number(askCount) || 0;
            
            console.log('当前库存:', currentInventory, '申请出库:', requestOutCount);
            
            // 如果库存不足，显示库存不足确认弹窗
            if (currentInventory < requestOutCount) {
                console.log('库存不足，显示确认弹窗');
                showInventoryShortageDialog(currentInventoryItem, requestOutCount);
                return false;
            }
        } else {
            // 如果没有找到库存信息，也视为库存不足
            console.log('未找到库存信息，创建虚拟库存项');
            const virtualInventoryItem = {
                productMaterialsName: currentMaterialAskItem.value?.productMaterialsName || '未知物料',
                productMaterialsId: materialId,
                currentInventory: 0
            };
            showInventoryShortageDialog(virtualInventoryItem, askCount);
            return false;
        }
        
        // 库存充足，继续执行出库操作
        // 生成出库编号
        const outInCode = 'CK' + Math.floor(100000 + Math.random() * 900000).toString();
        
        // 构建出库数据
        const outData = {
            outInCode: outInCode,
            outIn: 1, // 1表示出库
            outInCount: askCount,
            productMaterialsId: materialId,
            materialAskCode: currentMaterialAskItem.value?.materialAskCode || '',
            createrPeople: pinia.piniaDto.realName
        };
        
        console.log('提交出库数据:', outData);
        
        // 调用出库API
        const response = await axios.post('/api/ProductionModules/AddMaterialOut', outData);
        
        if (response.data.code === 200) {
            ElMessage.success(`${isEmergency ? '应急' : ''}扫码出库成功！`);
            
            // 关闭弹窗
            barcodeDialogVisible.value = false;
            
            // 更新本地申请记录的状态为已完成（后端状态由服务器自行处理）
            if (currentMaterialAskItem.value && currentMaterialAskItem.value.id) {
                await updateMaterialAskStatus(currentMaterialAskItem.value.id, '已完成');
            }
            
            // 刷新数据
            GetWare(); // 刷新库存数据
            fetchMaterialAskRecords(); // 刷新申请记录
            
            // 清空扫码输入框
            scanInputData.value = '';
            
            return true;
        } else {
            console.error('出库API返回错误:', response.data);
            ElMessage.error(response.data.message || '出库失败');
            return false;
        }
    } catch (error) {
        console.error('执行出库操作失败:', error);
        ElMessage.error('执行出库操作失败');
        throw error;
    }
};




/**
 * 生成物料出库编号
 */
const generateMaterialOutCode = () => {
    const randomNumber = Math.floor(100000 + Math.random() * 900000).toString();
    materialOutForm.outInCode = 'CK' + randomNumber;
    isMaterialOutCodeGenerated.value = true;
    ElMessage.success('出库编号已生成');
};

/**
 * 增加物料出库数量
 */
const increaseMaterialOutCount = () => {
    const currentCount = Number(materialOutForm.outInCount) || 0;
    materialOutForm.outInCount = currentCount + 1000;
};

/**
 * 减少物料出库数量
 */
const decreaseMaterialOutCount = () => {
    const currentCount = Number(materialOutForm.outInCount) || 0;
    if (currentCount >= 1000) {
        materialOutForm.outInCount = currentCount - 1000;
    } else {
        ElMessage.warning('出库数量不能小于0');
    }
};

/**
 * 提交物料出库表单
 */
const submitMaterialOutForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            try {
                console.log('提交物料出库数据:', materialOutForm);
                
                // 检查库存是否充足
                await checkInventoryBeforeOut();
                
            } catch (error) {
                console.error('物料出库失败:', error);
                ElMessage.error('出库操作失败，请重试');
            }
        } else {
            console.log('表单验证失败!', fields);
        }
    });
};

/**
 * 出库前检查库存
 */
const checkInventoryBeforeOut = async () => {
    try {
        // 根据物料ID查找当前库存信息
        const currentInventoryItem = tableData.value.find((item: any) => 
            item.productMaterialsId === materialOutForm.productMaterialsId || 
            item.id === materialOutForm.productMaterialsId
        );
        
        console.log('找到的库存信息:', currentInventoryItem);
        console.log('申请出库数量:', materialOutForm.outInCount);
        
        if (currentInventoryItem) {
            const currentInventory = Number((currentInventoryItem as any).currentInventory) || 0;
            const requestOutCount = Number(materialOutForm.outInCount) || 0;
            
            console.log('当前库存:', currentInventory, '申请出库:', requestOutCount);
            
            // 如果库存不足，显示库存不足确认弹窗
            if (currentInventory < requestOutCount) {
                console.log('库存不足，显示确认弹窗');
                showInventoryShortageDialog(currentInventoryItem, requestOutCount);
                return;
            }
        } else {
            // 如果没有找到库存信息，也视为库存不足
            console.log('未找到库存信息，创建虚拟库存项');
            const virtualInventoryItem = {
                productMaterialsName: materialOutForm.productMaterialsName,
                productMaterialsId: materialOutForm.productMaterialsId,
                currentInventory: 0
            };
            showInventoryShortageDialog(virtualInventoryItem, materialOutForm.outInCount);
            return;
        }
        
        // 库存充足，执行出库操作
        await executeActualMaterialOut();
        
    } catch (error) {
        console.error('检查库存失败:', error);
        ElMessage.error('检查库存失败，请重试');
    }
};

/**
 * 执行实际的物料出库操作
 */
const executeActualMaterialOut = async () => {
    try {
        console.log('库存充足，开始执行出库操作');
        
        // 调用出库API
        const response = await axios.post('/api/ProductionModules/AddMaterialOut', {
            outInCode: materialOutForm.outInCode,
            outIn: materialOutForm.outIn,
            outInCount: Number(materialOutForm.outInCount),
            productMaterialsId: materialOutForm.productMaterialsId,
            materialAskCode: materialOutForm.materialAskCode,
            createrPeople: materialOutForm.createrPeople
        });
        
        if (response.data.code === 200) {
            ElMessage.success('物料出库成功！');
            
            // 关闭弹窗
            materialOutDialogVisible.value = false;
            
            // 更新本地申请记录的状态为已完成（后端状态由服务器自行处理）
            if (currentMaterialAskItem.value && currentMaterialAskItem.value.id) {
                await updateMaterialAskStatus(currentMaterialAskItem.value.id, '已完成');
            }
            
            // 刷新数据
            GetWare(); // 刷新库存数据
            fetchMaterialAskRecords(); // 刷新申请记录
        } else {
            ElMessage.error(response.data.message || '出库失败');
        }
        
    } catch (error) {
        console.error('执行出库失败:', error);
        ElMessage.error('出库操作失败，请重试');
    }
};

/**
 * 更新物料申请状态 (仅更新本地数据，后端状态由服务器自行处理)
 * @param askId 申请记录ID
 * @param status 新状态
 */
const updateMaterialAskStatus = async (askId: any, status: string) => {
    try {
        console.log('更新本地申请状态:', askId, status);
        
        // 更新本地数据
        const askItem = materialAskList.value.find(item => item.id === askId);
        if (askItem) {
            askItem.materialAskStatus = status;
            console.log('本地状态已更新');
        } else {
            console.warn('未找到本地申请记录:', askId);
        }
        
    } catch (error) {
        console.error('更新本地申请状态失败:', error);
    }
};


// 显示库存不足确认弹窗
const showInventoryShortageDialog = (item: any, requestCount: number) => {
    console.log('显示库存不足弹窗:', item, requestCount);
    
    // 保存当前物料和数量信息
    currentShortageItem.value = { ...item };
    shortageRequestCount.value = requestCount;
    
    // 关闭一维码出库弹窗（如果打开）
    if (barcodeDialogVisible.value) {
        console.log('关闭一维码出库弹窗');
        barcodeDialogVisible.value = false;
    }
    
    // 显示库存不足弹窗
    inventoryShortageDialogVisible.value = true;
}

// 取消库存不足弹窗
const cancelShortageDialog = () => {
    inventoryShortageDialogVisible.value = false;
    currentShortageItem.value = {};
    shortageRequestCount.value = 0;
}

// 跳转到采购申请单页面
const goToPurchaseRequest = () => {
    try {
    // 关闭当前所有弹窗
    materialOutDialogVisible.value = false;
    inventoryShortageDialogVisible.value = false;
        barcodeDialogVisible.value = false;
        
        console.log('准备跳转到采购申请单页面');
        console.log('物料信息:', {
            materialName: currentShortageItem.value.productMaterialsName,
            materialId: currentShortageItem.value.productMaterialsId || currentShortageItem.value.id,
            shortageCount: shortageRequestCount.value - currentShortageItem.value.currentInventory,
            requestCount: shortageRequestCount.value
        });
    
    // 跳转到采购申请单页面，传递物料信息
    router.push({
        path: '/PurchaseRequest',
        query: {
            materialName: currentShortageItem.value.productMaterialsName,
            materialId: currentShortageItem.value.productMaterialsId || currentShortageItem.value.id,
            shortageCount: shortageRequestCount.value - currentShortageItem.value.currentInventory,
            requestCount: shortageRequestCount.value
        }
        }).catch(err => {
            console.error('路由跳转失败:', err);
            ElMessage.error('跳转到采购申请单页面失败');
    });
    } catch (error) {
        console.error('跳转到采购申请单页面时发生错误:', error);
        ElMessage.error('跳转失败，请手动导航到采购申请单页面');
    }
}
</script>

<style scoped>
.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px;
    background-color: #f9fafb;
    border-radius: 8px;
}

.custom-pagination {
    --el-pagination-item-size: 32px;
    --el-pagination-item-bg: #ffffff;
    --el-pagination-item-color: #606266;
    --el-pagination-item-hover-color: #4096ff;
    --el-pagination-item-active-color: #ffffff;
    --el-pagination-item-active-bg: #4096ff;
    --el-pagination-border-radius: 6px;
    --el-pagination-margin: 0 5px;
}

.custom-pagination .el-pagination__prev,
.custom-pagination .el-pagination__next {
    width: 32px;
    height: 32px;
    border-radius: 6px;
}

.custom-pagination .el-pagination__sizes {
    margin-right: 10px;
}

.custom-pagination .el-pagination__total {
    margin-right: 10px;
    color: #606266;
}

.custom-pagination .el-pagination__item {
    margin: 0 5px;
    border-radius: 6px;
    min-width: 32px;
    height: 32px;
    line-height: 32px;
}

.custom-pagination .el-pagination__item:hover {
    background-color: #f0f5ff;
}

.custom-pagination .el-pagination__item.is-active {
    background-color: #4096ff;
    color: #ffffff;
}

/* 物料申请记录筛选区域样式 */
.material-ask-filter {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f9fafb;
    border-radius: 8px;
}

/* 出库数量控制区域样式 */
.inventory-control {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}

.inventory-btn {
    flex: 0 0 auto;
    padding: 8px 12px;
    font-size: 16px;
    font-weight: bold;
}

.inventory-input {
    flex: 1;
    margin: 0 10px;
    text-align: center;
}

.inventory-input :deep(.el-input__inner) {
    text-align: center;
}

/* 库存不足弹窗样式 */
.shortage-info {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    padding: 20px;
    background-color: #fef0f0;
    border-radius: 8px;
    border: 1px solid #fde2e2;
}

.warning-icon {
    font-size: 48px;
    color: #f56c6c;
    flex-shrink: 0;
    margin-top: 5px;
}

.shortage-content {
    flex: 1;
}

.shortage-content h3 {
    margin: 0 0 15px 0;
    color: #f56c6c;
    font-size: 18px;
    font-weight: 600;
}

.shortage-content p {
    margin: 8px 0;
    color: #606266;
    line-height: 1.5;
}

.shortage-content strong {
    color: #303133;
}

.shortage-question {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
}

.shortage-question p {
    font-size: 16px;
    font-weight: 600;
    color: #409eff;
    margin: 0;
}

/* 出库成功状态样式 */
.completed-status {
    color: #e6a23c;
    font-weight: 600;
    font-size: 14px;
}

/* 操作按钮容器样式 */
.operation-buttons {
    display: flex;
    gap: 10px;
}

/* 一维码相关样式 */
.barcode-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
}

.barcode-display {
    margin: 20px 0;
    padding: 20px;
    background-color: white;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.barcode-canvas {
    max-width: 100%;
    height: auto;
}

.barcode-instructions {
    margin-top: 20px;
    text-align: center;
    color: #606266;
}

.barcode-note {
    margin-top: 10px;
    font-size: 14px;
    color: #909399;
}

.scan-input-container {
    margin-top: 20px;
    width: 100%;
    max-width: 300px;
}

.scan-input {
    width: 100%;
}

</style>
